<?php

declare(strict_types=1);

namespace app\wechat\controller;

use think\facade\View;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Message;
use EasyWeChat\Kernel\Messages\Text;
use app\model\UsersSessions;
use app\model\kefu\Xiansuo;

class UsersController
{

    public function wechat()
    {
        $backurl = input('get.backurl');

        $app = Factory::officialAccount(config('sysconfig.WeChatMP'));
        $oauth = $app->oauth;
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

        //回调地址
        $callback_url = $http_type . $_SERVER['HTTP_HOST'] . '/wechat/users/wechatres?backurl=' . urlencode($backurl);
        $response = $oauth->scopes(['snsapi_base'])->redirect($callback_url);

        // 将响应输出
        $response->send();
    }

    public function wechatres()
    {
        $app = Factory::officialAccount(config('sysconfig.WeChatMP'));
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        //print_r($user);

        $weid = weid();
        $tokenInfo = UsersSessions::where(['weid' => $weid, 'ptype' => 'weixin', 'token' => $user->getId()])->find();

        if (empty($tokenInfo)) {
            $data = $user;
            if (!empty($data)) {
                $data = serialize($data->toArray());
                UsersSessions::create(['weid' => $weid, 'ptype' => 'weixin', 'token' => $user->getId(), 'data' => $data]);
            }
        }

        $xiansuo =  Xiansuo::where(['chatid' => $user->getId()])->find();
        if (empty($xiansuo)) {
            Xiansuo::updataChat(['chatid' => $user->getId()]);
        }

        $backurl = input('get.backurl');
        $backurl = $backurl . '?openid=' . $user->getId();
        return redirect($backurl);
    }
}
